package com.tempjob.common.businesss.mongo.service.impl;

import com.anwen.mongo.service.impl.ServiceImpl;
import com.tempjob.common.businesss.mongo.entity.JobCategory;
import com.tempjob.common.businesss.mongo.service.JobCategoryService;
import com.tempjob.common.model.KeyValueModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author hui
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2024-02-18 18:57:52
*/
@Slf4j
@Service
public class JobCategoryServiceImpl extends ServiceImpl<JobCategory> implements JobCategoryService {

    @Override
    public List<KeyValueModel> buildTree(List<JobCategory> jobCategories) {
        // 创建一个List，用于存储根节点
        List<KeyValueModel> rootKeyValueList = jobCategories.stream().filter(i -> StringUtils.isBlank(i.getParentId())).map(s -> {
            return new KeyValueModel(s.getId(), s.getCategoryName(), s.getId(), new ArrayList<>());
        }).collect(Collectors.toList());
        for (KeyValueModel keyValueModel : rootKeyValueList) {
            buildSubTree(keyValueModel, jobCategories);
        }
        return rootKeyValueList;
    }

    // 递归构建子树
    private static void buildSubTree(KeyValueModel parentKeyValue, List<JobCategory> categoryList) {
        for (JobCategory jobCategory : categoryList) {
            if (StringUtils.isNotBlank(jobCategory.getParentId()) && jobCategory.getParentId().equals(parentKeyValue.getValue())) {
                List<KeyValueModel> childList = parentKeyValue.getChildren() == null ? new ArrayList<>() : parentKeyValue.getChildren();
                KeyValueModel child = new KeyValueModel(jobCategory.getId(), jobCategory.getCategoryName(), jobCategory.getId(), new ArrayList<>());
                buildSubTree(child, categoryList);
                childList.add(child);
                parentKeyValue.setChildren(childList);
            }
        }
    }

}




